package com.jajahome.feature.user.activity;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jajahome.R;
import com.jajahome.base.BaseActivity;
import com.jajahome.constant.Constant;
import com.jajahome.event.EventMessage;
import com.jajahome.feature.user.adapter.CrowItemAdapter;
import com.jajahome.feature.user.adapter.CrowItemHeadAdapter;
import com.jajahome.feature.user.adapter.CrowPagerAdapter;
import com.jajahome.model.BroadCastModel;
import com.jajahome.model.CrowModel;
import com.jajahome.model.LoginModle;
import com.jajahome.network.ApiImp;
import com.jajahome.network.BaseReq;
import com.jajahome.network.ReqPage;
import com.jajahome.util.LoginUtil;
import com.jajahome.widget.AutoListView;
import com.jajahome.widget.banner.SyAutoScrollViewPager;
import com.jajahome.widget.banner.SyCirclePageIndicator;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by tuxuesong on 2018/5/28.
 */

public class CrowAct extends BaseActivity {

    public static final int CROW_ACTION = 0x999;
    @BindView(R.id.autoScroll)
    SyAutoScrollViewPager viewPager;
    @BindView(R.id.indicator)
    SyCirclePageIndicator indicator;
    @BindView(R.id.ibtn_back)
    ImageButton imageButton;
    @BindView(R.id.container)
    LinearLayout cLayout;
    @BindView(R.id.main)
    ScrollView mainLayout;
    @BindView(R.id.display)
    TextView disPlayer;
    @BindView(R.id.textView2)
    TextView title;

    private boolean isok = false;
    private CrowItemHeadAdapter headAdapter;
    private CrowPagerAdapter adapters;
    private CrowItemAdapter adapter;
    private MyThread timeThread;
    private List<CrowModel.DataEntity.CrowdListEntity> crowList = new ArrayList<>();
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (crowList.size() == 0) {
                        mainLayout.setVisibility(View.GONE);
                        disPlayer.setVisibility(View.VISIBLE);
                        disPlayer.setText("暂时未有众筹项目...");
                    }
                    getTopData();
                    break;
            }
        }
    };


    @Override
    protected int getViewId() {
        return R.layout.act_crow_item;
    }

    @Override
    protected void initEvent() {
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        title.setText("众筹");
        setLayout();
    }

    // 众筹状态  -1 所有   ０即将开始，１正在众筹，２众筹成功结束，3 众筹失败结束 ， 4 成功状态已处理 ， 5 失败状态已处理'
    private void getList(final int state, final AutoListView listView, final TextView textView, final LinearLayout ll) {
        try {
            if (state == 3) {
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ReqPage.ContentBean.PaginationBean paginationBean = new ReqPage.ContentBean.PaginationBean();
        ReqPage.ContentBean contentBean = new ReqPage.ContentBean();
        contentBean.setState(state);
        contentBean.setPagination(paginationBean);
        ReqPage reqPage = new ReqPage();
        reqPage.setContent(contentBean);
        reqPage.setCmd(Constant.crowd_funding_list);
        final Gson gson = new Gson();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), gson.toJson(reqPage));
        RequestBody requestBodyl = RequestBody.create(MediaType.parse("application/session"), gson.toJson(LoginUtil.getInfo(mContext).getData().getSession()));
        ApiImp.get().crow_act(requestBody, requestBodyl)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CrowModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(CrowModel model) {
                        crowList.addAll(model.getData().getCrowdList());
                        int size = model.getData().getCrowdList().size();
                        if (state == 0 && size > 0) {
                            List<CrowModel.DataEntity.CrowdListEntity> refreshList = model.getData().getCrowdList();
                            headAdapter = new CrowItemHeadAdapter(mContext, refreshList);
                            listView.setAdapter(headAdapter);
                            timeThread = new MyThread(refreshList);
                            new Thread(timeThread).start();
                        } else {
                            adapter = new CrowItemAdapter(mContext, model.getData().getCrowdList());
                            listView.setAdapter(adapter);
                        }
                        if (size == 0) {
                            ll.setVisibility(View.GONE);
                            textView.setVisibility(View.GONE);
                        } else {
                            ll.setVisibility(View.VISIBLE);
                            textView.setVisibility(View.VISIBLE);
                        }
                        //判断state为2是否有数据
                        if (size != 0 && state == 2) {
                            isok = true;
                        }
                        if (state == 3) {
                            if (isok) {
                                ll.setVisibility(View.GONE);
                                textView.setVisibility(View.GONE);
                            } else {
                                if (size == 0) {
                                    ll.setVisibility(View.GONE);
                                    textView.setVisibility(View.GONE);
                                } else {
                                    ll.setVisibility(View.VISIBLE);
                                    textView.setVisibility(View.VISIBLE);
                                    isok = true;
                                }
                            }
                            mHandler.sendEmptyMessage(1);
                        }
                        if (isok) {//2或者3是有数据的，以2或者3为主
                            if (state == 4) {
                                textView.setVisibility(View.GONE);
                                ll.setVisibility(View.GONE);
                            } else if (state == 5) {
                                textView.setVisibility(View.GONE);
                                ll.setVisibility(View.GONE);
                                isok = false;
                            }
                        } else {//2.3都没有,4有为主，没有5为主
                            if (size != 0 && state == 4) {
                                textView.setVisibility(View.VISIBLE);
                                ll.setVisibility(View.VISIBLE);
                                isok = true;
                            }
                            if (state == 5) {
                                if (isok) {
                                    ll.setVisibility(View.GONE);
                                    textView.setVisibility(View.GONE);
                                } else {
                                    if (size == 0) {
                                        ll.setVisibility(View.GONE);
                                        textView.setVisibility(View.GONE);
                                    } else {
                                        textView.setVisibility(View.VISIBLE);
                                        ll.setVisibility(View.VISIBLE);
                                    }
                                }
                                isok = false;
                            }
                        }

                    }
                });

    }


    private void setLayout() {
        cLayout.removeAllViews();
        crowList.clear();
        for (int i = 0; i < 6; i++) {
            LinearLayout ll = new LinearLayout(mContext);
            ll.setOrientation(LinearLayout.HORIZONTAL);
            ll.setVisibility(View.GONE);
            ll.setGravity(Gravity.CENTER);
            ImageView iv = new ImageView(mContext);
            iv.setMaxHeight(60);
            iv.setMaxWidth(60);
            TextView textView = new TextView(mContext);
            textView.setPadding(0, 10, 0, 10);
            textView.setGravity(Gravity.CENTER_HORIZONTAL);
            textView.setTypeface(Typeface.DEFAULT_BOLD);
            textView.setTextSize(mContext.getResources().getDimension(R.dimen.text_size_8));
            textView.setTextColor(Color.BLACK);
            textView.setVisibility(View.GONE);
            AutoListView listView = new AutoListView(mContext);
            //添加底部的分割线
            listView.addFooterView(new ViewStub(this));
            ll.addView(iv);
            ll.addView(textView);
            cLayout.addView(ll);
            cLayout.addView(listView);
            int j = 0;
            switch (i) {
                case 0:
                    iv.setImageResource(R.mipmap.icon_crowdfunding);
                    textView.setText("正在众筹");
                    j = 1;
                    break;
                case 1:
                    iv.setImageResource(R.mipmap.icon_start);
                    textView.setText("即将开始");
                    j = 0;
                    break;
                case 2:
                case 3:
//                    j = i;
//                    textView.setText("众筹结束");
//                    break;
                case 4:
                case 5:
//                    textView.setText("已过众筹期");
                    iv.setImageResource(R.mipmap.icon_end);
                    textView.setText("众筹结束");
                    j = i;
                    break;
            }
            getList(j, listView, textView, ll);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timeThread != null) {
            timeThread.endThread = true;
        }
    }

    private List<CrowModel.DataEntity.CrowdListEntity> list = new ArrayList<>();

    private void getTopData() {
        BaseReq req = new BaseReq();
        req.setCmd(Constant.CROWD_FUNDING_LIST_BROADCAST);
        final Gson gson = new Gson();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), gson.toJson(req));
        ApiImp.get().crowd_funding_list_broadcast(requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BroadCastModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BroadCastModel crowModel) {
                        list.clear();
                        if (crowList.size() > 0 && crowModel != null) {
                            List<BroadCastModel.DataEntity.CrowdFundingEntity> crowd_funding = crowModel.getData().getCrowd_funding();
                            for (BroadCastModel.DataEntity.CrowdFundingEntity bean : crowd_funding) {
                                for (CrowModel.DataEntity.CrowdListEntity bean1 : crowList) {
                                    if (bean.getId().equals(bean1.getId())) {
                                        list.add(bean1);
                                    }
                                }
                            }
                            if (adapters == null) {
                                adapters = new CrowPagerAdapter(getSupportFragmentManager(), list);
                                viewPager.setAdapter(adapters);
                                indicator.setViewPager(viewPager);
                                if (viewPager != null) {
                                    viewPager.startAutoScroll();
                                    viewPager.setInterval(2000);
                                }
                            } else {
                                adapters = new CrowPagerAdapter(getSupportFragmentManager(), list);
                                viewPager.setAdapter(adapters);
                                indicator.setViewPager(viewPager);
                                if (viewPager != null) {
                                    viewPager.startAutoScroll();
                                    viewPager.setInterval(2000);
                                }
                            }
                        }
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (viewPager != null) {
            viewPager.startAutoScroll();
            viewPager.setInterval(2000);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (viewPager != null) {
            viewPager.stopAutoScroll();
        }
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 2:
                    List<CrowModel.DataEntity.CrowdListEntity> list = (List<CrowModel.DataEntity.CrowdListEntity>) msg.obj;
                    headAdapter.notifyData(list);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void onEventMainThread(EventMessage event) {
        super.onEventMainThread(event);
        int act = event.action;
        if (act == CROW_ACTION) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            setLayout();
        }
    }

    class MyThread implements Runnable {
        //用来停止线程
        volatile boolean endThread = false;
        private List<CrowModel.DataEntity.CrowdListEntity> list1;

        public MyThread(List<CrowModel.DataEntity.CrowdListEntity> list1) {
            this.list1 = list1;
        }

        @Override
        public void run() {
            while (!endThread) {
                try {
                    Thread.sleep(1000);
                    for (int i = 0; i < list1.size(); i++) {
                        Long countdown = list1.get(i).getCountdown();
                        list1.get(i).setCountdown(countdown - 1);
                    }
                    Message message = new Message();
                    message.obj = list1;
                    message.what = 2;
                    //发送信息给handler
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
